/**
*在服务器端系统中安装Node.js运行环境；
*然后在命令行中进入当前目录，运行node index.js以启动WebSocket服务器程序 
*/
const WebSocket = require('ws');
const uuid = require('uuid');
const { StringDecoder } = require('string_decoder');
const port = 8800

const server = new WebSocket.Server({ port });		//WS服务器
const clients = new Map();							//所有连接到WS服务器的WS客户端集合
const decoder = new StringDecoder('utf8');

server.on('connection', (ws) => {
  const clientId = uuid.v4();
  clients.set(clientId, ws);
  console.log(`Client ${clientId} connected`);

  ws.send(`Welcome! New friend！`);					//WS协议采用“全双工通信”，服务器或客户端可以给对方一次性发送多个消息
  ws.send(`Your ID: ${clientId}`);

  ws.on('message', (data) => {
	broadcast(decoder.write(data), clientId);
  });

  ws.on('close', () => {
    clients.delete(clientId);
    broadcast(`Client ${clientId} disconnected`);
  });
});

function broadcast(message, excludeClientId = null) {
  clients.forEach((client, id) => {
    //if (client.readyState === WebSocket.OPEN && id !== excludeClientId) {			//把客户端消息转发给发送者之外的所有人
	if (client.readyState === WebSocket.OPEN ) {	//把客户端消息转发给所有人(包括发送者自己)
      client.send(message);
    }
  });
}

console.log(`WebSocket Server App started successfully; \nClient Apps can connect using ws://[ServerIP]:${port}\n`);
